<template>
  <el-card class="login-card">
    <el-form :model="form" @submit.prevent="onRegister">
      <el-form-item label="用户ID">
        <el-input v-model="form.id" />
      </el-form-item>
      <el-form-item label="用户名">
        <el-input v-model="form.username" />
      </el-form-item>
      <el-form-item label="密码">
        <el-input v-model="form.password" type="password" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onRegister" :loading="loading">注册</el-button>
        <el-button type="text" @click="goLogin">返回登录</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { registerAPI } from '@/api/userAPI'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const userStore = useUserStore()
const form = ref({ id: '', username: '', password: '' })
const loading = ref(false)

const onRegister = async () => {
  loading.value = true
  try {
    const res = await registerAPI(form.value.id, form.value.username, form.value.password)
    if (res.code === 200) {
      // 注册成功后自动登录
      userStore.setUser({
        id: res.data.user_id,
        token: res.data.token,
        username: res.data.username,
        email: res.data.user_email,
      })
      ElMessage.success('注册成功，已自动登录')
      router.push('/')
    } else {
      ElMessage.error(res.msg)
    }
  } catch (e) {
    ElMessage.error('注册失败'+e)
  } finally {
    loading.value = false
  }
}

const goLogin = () => {
  router.push('/login')
}
</script>

<style scoped>
.login-card {
  max-width: 400px;
  margin: 100px auto;
}
</style>
